<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import GalleryCar2 from '@/components/gallery/car/galleryCar2.vue'
import { useArticle } from '@/hooks/articleHook'; // 文章数据管理hook
import type { articleData } from '@/utils/interface'

// 获取文章数据和列表
const {
    getArticle,
    articlCount,
    articleList, // 文章列表数据
} = useArticle(); // 文章管理hook

const props = defineProps({
    pageSize: {
        type: Number,
        default: 8, // 每页数量
    },
    subsetId: {
        type: [Number,String],
        default: -1, // 分类筛选
    },
    searchTerm: {
    type: String,
     default: '',
   },
    isChangeSmall: {
        type: Boolean,
        default: false, // 是否使用小尺寸布局
    },
})

// 文章查询参数
const request = {
    pageSize: props.pageSize, // 每页数量
    nowPage: 1, // 当前页码
    state: 1, // 只显示已发布
    subset_id: props.subsetId, // 分类筛选
    searchTerm: props.searchTerm, // 搜索词
    classify: 1, // 分类类型
    count: true, // 是否返回总数
}
// 分页状态
const currentPage = ref(1);
const isLoading = ref(false);
const hasMore = ref(true);

//文章列表
const articles = ref<articleData[]>([]);
// 监听articleList变化，更新articles
watch(articleList, (newVal) => {
  articles.value.push(...newVal);
  // 检查是否加载完所有文章
    if(articles.value.length===articlCount.value) {
    hasMore.value = false;
  };
  console.log('articles', articles.value);

})


// 加载更多文章
const loadMore = async () => {
  if (isLoading.value || !hasMore.value) return;
  isLoading.value = true;
  currentPage.value++;
  request.nowPage = currentPage.value;
  try {
    getArticle(request);
  } catch (error) {
    console.error('加载失败:', error);
    currentPage.value--; // 回滚页码
  } finally {
    isLoading.value = false;
  }
}

// 防抖函数
let timer: ReturnType<typeof setTimeout> | null = null;
const debounceLoadMore = () => {
  if (timer) clearTimeout(timer);
  timer = setTimeout(() => {
    loadMore();
  }, 300);
}

watch(() => [props.subsetId, props.searchTerm], () => {
  request.subset_id = props.subsetId;
  request.searchTerm = props.searchTerm;
  articles.value = [];
  currentPage.value = 1;
  hasMore.value = true;
  console.log('props.subsetId', request);
  getArticle(request);
})



// 组件挂载时加载文章数据
onMounted(() => {
    getArticle(request);
})

</script>

<template>
    <GalleryCar2 :articleList="articles" :isChangeSmall="isChangeSmall" :currentIndex="-1" :searchTerm="props.searchTerm" />
        <!-- 加载更多按钮 -->
  <div class="w-full flex justify-center items-center mb-10">
    <button :disabled="isLoading || !hasMore" :class="[
      'border-2 text-xl px-4 py-2 rounded-full cursor-pointer transition-all duration-300',
      isLoading || !hasMore
        ? 'bg-gray-300 text-gray-500 cursor-not-allowed'
        : 'hover:bg-amber-500 hover:scale-105'
    ]" @click="debounceLoadMore"> {{ isLoading ? '加载中...' : hasMore ? '加载更多' : '没有更多了' }}</button>
  </div>
</template>

<style scoped>

</style>
